<?php

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Thu, 1 Jan 1970 01:00:00 GMT"); // Date in the past
//header('Content-type: text/html');
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
ini_set('log_errors', '1');
ini_set('error_log', 'php_error.log');
ini_set('display_errors', '1');


$appId = "140410776032411";
$appSecret = "fb2894b6ece45f1371ce316818e94a88";

$host = $_SERVER['HTTP_HOST'];
$uri = trim(dirname($_SERVER['PHP_SELF']), '/\\');

$code = $_REQUEST["code"];
$callback = !empty($_REQUEST['callback']) ? $_REQUEST['callback'] : 'fbAuthCallback';
$returnUrl = !empty($_REQUEST['returnUrl']) ? $_REQUEST['returnUrl'] : "http://$host/play/facebook.html";

$myUrl = "http://$host/$uri/fb.auth.php";

if (FALSE) {
	if (empty($code)) {
		$dialogUrl = "http://www.facebook.com/dialog/oauth?scope=publish_stream&client_id={$appId}&redirect_uri=" . urlencode($myUrl);
		$context = stream_context_create(array(
		    'http' => array(
			'user_agent' => $_ENV['HTTP_USER_AGENT']
		    )
			));
		$reply = file_get_contents($dialogUrl, false, $context);
		header('Content-type: text/html');
		echo $reply;
		exit(0);
	}
} else {
	if (empty($code)) {
		$dialogUrl = "http://www.facebook.com/dialog/oauth?scope=publish_stream&client_id={$appId}&redirect_uri=" . urlencode($myUrl);
		header("Location: $dialogUrl");
		exit(0);
	}
}
$token_url = "https://graph.facebook.com/oauth/access_token?client_id={$appId}&redirect_uri=" . urlencode($myUrl) . "&client_secret={$appSecret}&code={$code}";

$accessToken = file_get_contents($token_url);

$returnFullUrl = "$returnUrl?$accessToken";
header("Location: $returnFullUrl");
?>